#include "StringConverter.h"


uint16_t IntToChar_g(int32_t source, uint8_t *target)
{
	uint16_t length = 0;
    int8_t i=0,flag=0;
	int32_t temp=0,n=0;

	if(source==0)
	{
		(target)[0] = '0';
		return 1;
	}

	if (source < 0)
	{
		flag = length = 1;
		source = -source;
	}
	temp = source;
	while (temp > 0)
	{
		length++;
		n = temp % 10;
		temp = (temp - n) / 10;

	}

	/*itoa(temp, *target, 10);*/
	if(flag==1)
		(target)[0] = '-';

	temp = source;
	n = temp % 10;
	for (i = length-1; i>=flag; i--)
	{
		(target)[i] = n + '0';
		temp = (temp - n) / 10;
		n = temp % 10;
	}

	return length;
}

//字节流转换为十六进制字符串，高位在前
uint16_t ByteToHexStr_g(uint8_t* source, uint8_t sourceLen, uint8_t* dest,uint8_t highIsFirst)
{
	uint8_t i;
	uint8_t highByte, lowByte;
	uint16_t strLength = sourceLen * 3 - 1;

	if(highIsFirst)
	{
		for (i = 0; i < sourceLen; i++)
		{
			highByte = source[sourceLen-i-1] >> 4 & 0x0f;
			lowByte = source[sourceLen-i-1] & 0x0f;

			highByte += 0x30;

			if (highByte > 0x39)
				(dest)[i * 3] = highByte + 0x07;
			else
				(dest)[i * 3] = highByte;

			lowByte += 0x30;
			if (lowByte > 0x39)
				(dest)[i * 3 + 1] = lowByte + 0x07;
			else
				(dest)[i * 3 + 1] = lowByte;

			if(i!=sourceLen-1)
				(dest)[i * 3 + 2] = ' ';
		}
	}
	else
	{
			for (i = 0; i < sourceLen; i++)
			{
				highByte = source[i] >> 4 & 0x0f;
				lowByte = source[i] & 0x0f;

				highByte += 0x30;

				if (highByte > 0x39)
					(dest)[i * 3] = highByte + 0x07;
				else
					(dest)[i * 3] = highByte;

				lowByte += 0x30;
				if (lowByte > 0x39)
					(dest)[i * 3 + 1] = lowByte + 0x07;
				else
					(dest)[i * 3 + 1] = lowByte;

				if(i!=sourceLen-1)
					(dest)[i * 3 + 2] = ' ';
			}
		}
	return strLength;
}

//uint转换成16进制字符串，高位在前
uint16_t UIntToHexStr_g(uint32_t source, uint8_t* dest)
{
	uint8_t i;
	uint8_t onechar;
	uint16_t byteLength = 8+2;

	(dest)[0] = '0';
	(dest)[1] = 'x';
	for (i = 2; i < byteLength; i++)
	{
		onechar = (source>>(4*(byteLength -i-1))) & 0x0f;

		onechar += 0x30;

		if (onechar > 0x39)
			(dest)[i] = onechar + 0x07;
		else
			(dest)[i] = onechar;

	}
	return byteLength;
}
